package com.yantong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.yantong.constant.StringConstans;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.BusinessTimeVo;
import com.yantong.service.CentreService;
import com.yantong.service.ConfigService;
import com.yantong.service.StoreService;
import com.yantong.service.WxService;
import com.yantong.utils.DateUtils;
import com.yantong.utils.QRCodeUtil;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.*;

@Service
public class StoreServiceImpl implements StoreService {

	private static final Logger logger = LoggerFactory.getLogger(StoreServiceImpl.class);

	@Autowired
	private StoreMapper storeMapper;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private StoreWxCardMapper storeWxCardMapper;
	@Autowired
	private MemberWxcardMapper memberWxcardMapper;
	@Autowired
	private StoreFreechargeMapper storeFreechargeMapper;
	@Autowired
	private WxService wxService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private CentreService centreService;
	@Value("${Applet.TemplatemsgCreateUserUrl}")
	private String templatemsgCreateUserUrl = "";

	@Override
	public Store getStoreByTeamid(Long teamid) {
		Store store = storeMapper.selectByTeamid(teamid);
		if (store != null && StringUtils.isNotEmpty(store.getBusinessBeginTime())) {
			List<String> timeStrList = Arrays.asList(store.getBusinessBeginTime().split("-"));
			List<BusinessTimeVo> timeList = new ArrayList<>();
			for (String str : timeStrList) {
				BusinessTimeVo vo = JSON.parseObject(str, BusinessTimeVo.class, Feature.OrderedField);
				timeList.add(vo);
			}
			store.setBusinessTimeList(timeList);
		}
		return store;
	}

	@Override
	public int updateFreeChargeDescByTeamId(Store store) {
		Store currentStore = storeMapper.selectByTeamid(store.getTeamid());
		int updateCount = 0;
		if (null != currentStore) {
			currentStore.setFreechargeDesc(store.getFreechargeDesc());
			currentStore.setNotice(store.getNotice());
			currentStore.setDiscountRule(store.getDiscountRule());
			currentStore.setShopEnv(store.getShopEnv());
			updateCount = storeMapper.updateByPrimaryKeySelective(currentStore);
		} else {
			Member shopMember = memberMapper.selectByPrimaryKey(store.getTeamid());
			if (null != shopMember) {
				currentStore = new Store();
				currentStore.setTeamid(store.getTeamid());
				currentStore.setStoreName(shopMember.gettXiaoqu());
				currentStore.setFreechargeDesc(store.getFreechargeDesc());
				currentStore.setLatitude(shopMember.gettLat());
				currentStore.setLongitude(shopMember.gettLng());
				currentStore.setNotice(store.getNotice());
				currentStore.setDiscountRule(store.getDiscountRule());
				currentStore.setShopEnv(store.getShopEnv());
				updateCount = storeMapper.insertSelective(currentStore);
			}
		}
		return updateCount;
	}

	@Override
	public Map<String, String> getShopCardInfo(Member member, Long shopMemberId, int type) {
		logger.info("===========领取卡包memberId = {} , shopMemberId={} , type = {}",member.getId(),shopMemberId,type);
		Map<String, String> resultMap = new HashMap<>();
		String cardId = StringConstans.STR_EMPTY;
		Member shopMemeber = new Member();
		Centre centre = new Centre();
		if(type == 1) {
			 shopMemeber = memberMapper.selectByPrimaryKey(shopMemberId);
		}else if(type == 2){ //如果为商户卡类型那么查询总门店
			 shopMemeber = memberMapper.selectByCentreIdAndIsHeadOffice(member.getCentreId(),1);
			 centre = centreService.getCentreById(member.getCentreId());
		}
		//查询门店信息，判断card信息是否存在
		StoreWxCardExample example = new StoreWxCardExample();
		if(type == 1) { //如果为门店卡类型
			example.createCriteria().andMidEqualTo(shopMemberId).andTypeEqualTo(1);
		}else if(type == 2) { //如果为商户卡类型
			example.createCriteria().andCentreIdEqualTo(member.getCentreId()).andTypeEqualTo(2);
		}
		List<StoreWxCard> storeWxCards = storeWxCardMapper.selectByExample(example);
		//存在则直接获取卡券ID
		if (ValidateUtil.isNotEmptyCollection(storeWxCards)) {
			cardId = storeWxCards.get(0).getCardId();
		}
		//不存在，则需要创建卡券
		else {
			Centre platCentre = centreService.getPlatCenter();
			//获取本地生活配置
			LifeConfig lifeConfig = configService.getLifeConfig(platCentre.getCentreId());
			String imgUrl = "";
			String logoUrl = "";
			Color color = null;
			if (lifeConfig != null) {
				if(type == 1) {
					if (ValidateUtil.isNotEmptyString(lifeConfig.getRefRegisterCouponImgUrl())) {
						imgUrl = lifeConfig.getRefRegisterCouponImgUrl();
						color = new Color(246,222,35);
					}
				}else{
					if (ValidateUtil.isNotEmptyString(lifeConfig.getCentreRefRegisterCouponImgUrl())) {
						imgUrl = lifeConfig.getCentreRefRegisterCouponImgUrl();
						color = new Color(118,88,39);
					}
				}
				if (ValidateUtil.isNotEmptyString(lifeConfig.getRefRegisterLogoImgUrl())) {
					logoUrl = lifeConfig.getRefRegisterLogoImgUrl();
					logger.info("=0=logoUrl==" + logoUrl);
				}
			}else {
				logger.info("======================================= lifeConfig为null  =======================================================");
			}
			logger.info("=0=imgUrl==" + imgUrl);
			String cardName = "";
			if(type == 1) { //如果类型为会员卡
				if(shopMemeber.getIsHeadOffice() == 1){
					cardName = "本地生活";
				}else{
					cardName = shopMemeber.gettXiaoqu();
				}
			}else if(type == 2){
				cardName = "本地生活";
			}

			try {
				BufferedImage bufferedImage = QRCodeUtil.referrerEncode(color,cardName, imgUrl);

				//图片不走阿里云  直接转换成inputStream   然后上传到微信
				ByteArrayOutputStream bs = new ByteArrayOutputStream();
				ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
				ImageIO.write(bufferedImage, "PNG", imOut);
				InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
				String imgUrlResponseJson = wxService.wxUploadImg(true, imgUrl, member.getCentreId(), inputStream);
				imgUrl = JSONObject.parseObject(imgUrlResponseJson).getString("url");
				logger.info("==imgUrl==" + imgUrl);

				String logoUrlResponseJson = wxService.wxUploadImg(true, logoUrl, member.getCentreId(), getImageStream(logoUrl));
				logoUrl = JSONObject.parseObject(logoUrlResponseJson).getString("url");
				logger.info("==logoUrl==" + logoUrl);
			} catch (Exception e) {
				e.printStackTrace();
			}

			Map<String, Object> createCardData = new HashMap<>();
			Map<String, Object> cardData = new HashMap<>();
			createCardData.put("card", cardData);
			cardData.put("card_type", "MEMBER_CARD");
			WxCardGroupon wxCardGroupon = new WxCardGroupon();
			cardData.put("member_card", wxCardGroupon);
			wxCardGroupon.background_pic_url = imgUrl;
			wxCardGroupon.base_info = new WxCardBaseInfo();
			wxCardGroupon.base_info.logo_url = logoUrl;
			//wxCardGroupon.base_info.brand_name = shopMemeber.gettXiaoqu();
			if(type == 1) { //如果类型为会员卡
				wxCardGroupon.base_info.brand_name = "商圈联盟";
				wxCardGroupon.base_info.title = "特权卡";
			}else if(type == 2){
				wxCardGroupon.base_info.brand_name = "商圈联盟";
				wxCardGroupon.base_info.title = "共享贵宾卡";
			}
			wxCardGroupon.base_info.code_type = "CODE_TYPE_QRCODE";
			//wxCardGroupon.base_info.title = shopMemeber.gettXiaoqu() + "会员卡";

			wxCardGroupon.base_info.color = "Color010";
			wxCardGroupon.base_info.notice = "使用时向服务员出示此券";
			wxCardGroupon.base_info.service_phone = "020-83622627";
			wxCardGroupon.base_info.description = "不可与其他优惠同享";
//			wxCardGroupon.base_info.date_info = new DateInfo();
//			wxCardGroupon.base_info.date_info.type = "DATE_TYPE_PERMANENT";
			wxCardGroupon.base_info.date_info = new WxCardBaseInfo.DateInfo();
			wxCardGroupon.base_info.date_info.type = "DATE_TYPE_FIX_TIME_RANGE";
			Date date = new Date();
			wxCardGroupon.base_info.date_info.begin_timestamp = (int)(date.getTime()/1000);
			wxCardGroupon.base_info.date_info.end_timestamp = (int)(DateUtils.getAddYearDate(date,1).getTime()/1000);
			wxCardGroupon.base_info.sku = new WxCardBaseInfo.Sku();
			wxCardGroupon.base_info.sku.quantity = 50000000L;
			wxCardGroupon.base_info.get_limit = 1;
			wxCardGroupon.base_info.use_custom_code = false;
			wxCardGroupon.base_info.can_give_friend = true;
			wxCardGroupon.base_info.location_id_list = new ArrayList<>();
			wxCardGroupon.base_info.location_id_list.add(123);
			wxCardGroupon.base_info.location_id_list.add(12321);
			wxCardGroupon.base_info.center_title = "进入会员特权";
			wxCardGroupon.base_info.center_url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html?teamid=" + shopMemeber.getId();
			wxCardGroupon.base_info.center_sub_title = "吃喝玩乐百亿补贴";
			wxCardGroupon.base_info.custom_url_name = "进入券包";
			wxCardGroupon.base_info.custom_url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/card-package";
			wxCardGroupon.base_info.custom_url_sub_title = "乐享百亿补贴";
			wxCardGroupon.base_info.promotion_url_name = "立即分享";
			wxCardGroupon.base_info.promotion_url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/my-poster";
			wxCardGroupon.base_info.need_push_on_view = true;
			wxCardGroupon.advanced_info = new WxCardGroupon.AdvancedInfo();
			wxCardGroupon.advanced_info.use_condition = new WxCardGroupon.UseCondition();
			wxCardGroupon.advanced_info.use_condition.accept_category = "鞋类";
			wxCardGroupon.advanced_info.use_condition.reject_category = "阿迪达斯";
			wxCardGroupon.advanced_info.use_condition.can_use_with_other_discount = true;
//            wxCardGroupon.advanced_info.abstractInfo = new WxCardGroupon.AbstractInfo();
//            wxCardGroupon.advanced_info.abstractInfo.abstractInfo = "微信餐厅推出多种新季菜品，期待您的光临";
//            wxCardGroupon.advanced_info.abstractInfo.icon_url_list = new ArrayList<>();
//            wxCardGroupon.advanced_info.abstractInfo.icon_url_list.add("http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0");
			wxCardGroupon.advanced_info.text_image_list = new ArrayList<>();
			WxCardGroupon.ImageValue imageValue1 = new WxCardGroupon.ImageValue();
			imageValue1.image_url = "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0";
			imageValue1.text = "此菜品精选食材，以独特的烹饪方法，最大程度地刺激食 客的味蕾";
			wxCardGroupon.advanced_info.text_image_list.add(imageValue1);
			WxCardGroupon.ImageValue imageValue2 = new WxCardGroupon.ImageValue();
			imageValue2.image_url = "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0";
			imageValue2.text = "此菜品迎合大众口味，老少皆宜，营养均衡";
			wxCardGroupon.advanced_info.text_image_list.add(imageValue2);
			wxCardGroupon.advanced_info.time_limit = new ArrayList<>();
			WxCardGroupon.TimeLimit timeLimit1 = new WxCardGroupon.TimeLimit();
			timeLimit1.type = "MONDAY";
//			timeLimit1.begin_hour = 0;
//			timeLimit1.end_hour = 23;
//			timeLimit1.begin_minute = 0;
//			timeLimit1.end_minute = 59;
			wxCardGroupon.advanced_info.time_limit.add(timeLimit1);
			WxCardGroupon.TimeLimit timeLimit2 = new WxCardGroupon.TimeLimit();
			timeLimit2.type = "TUESDAY";
			wxCardGroupon.advanced_info.time_limit.add(timeLimit2);

			WxCardGroupon.TimeLimit timeLimit3 = new WxCardGroupon.TimeLimit();
			timeLimit3.type = "WEDNESDAY";
			wxCardGroupon.advanced_info.time_limit.add(timeLimit3);

			WxCardGroupon.TimeLimit timeLimit4 = new WxCardGroupon.TimeLimit();
			timeLimit4.type = "THURSDAY";
			wxCardGroupon.advanced_info.time_limit.add(timeLimit4);

			WxCardGroupon.TimeLimit timeLimit5 = new WxCardGroupon.TimeLimit();
			timeLimit5.type = "FRIDAY";
			wxCardGroupon.advanced_info.time_limit.add(timeLimit5);

			WxCardGroupon.TimeLimit timeLimit6 = new WxCardGroupon.TimeLimit();
			timeLimit6.type = "SATURDAY";
			wxCardGroupon.advanced_info.time_limit.add(timeLimit6);

			WxCardGroupon.TimeLimit timeLimit7 = new WxCardGroupon.TimeLimit();
			timeLimit7.type = "SUNDAY";
			wxCardGroupon.advanced_info.time_limit.add(timeLimit7);
			wxCardGroupon.advanced_info.business_service = new ArrayList<>();
			wxCardGroupon.advanced_info.business_service.add("BIZ_SERVICE_FREE_WIFI");
			wxCardGroupon.advanced_info.business_service.add("BIZ_SERVICE_WITH_PET");
			wxCardGroupon.advanced_info.business_service.add("BIZ_SERVICE_FREE_PARK");
			wxCardGroupon.advanced_info.business_service.add("BIZ_SERVICE_DELIVER");
			wxCardGroupon.supply_bonus = true;
			wxCardGroupon.supply_balance = false;
			wxCardGroupon.prerogative = "test_prerogative";
			wxCardGroupon.auto_activate = true;
			wxCardGroupon.custom_field1 = new WxCardGroupon.CustomField();
			wxCardGroupon.custom_field1.name_type = "FIELD_NAME_TYPE_LEVEL";
			wxCardGroupon.custom_field1.url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html";
			wxCardGroupon.activate_url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html";
			wxCardGroupon.bonus_rule = new WxCardGroupon.BonusRule();
			wxCardGroupon.bonus_rule.cost_money_unit = 100;
			wxCardGroupon.bonus_rule.increase_bonus = 1;
			wxCardGroupon.bonus_rule.max_increase_bonus = 200;
			wxCardGroupon.bonus_rule.init_increase_bonus = 10;
			wxCardGroupon.bonus_rule.cost_bonus_unit = 5;
			wxCardGroupon.bonus_rule.reduce_money = 100;
			wxCardGroupon.bonus_rule.least_money_to_use_bonus = 1000;
			wxCardGroupon.bonus_rule.max_reduce_bonus = 50;
			wxCardGroupon.discount = 18;
			cardId = wxService.createCard(member.getCentreId(), JSONObject.toJSONString(createCardData));
			if (ValidateUtil.isEmptyString(cardId)) {
				throw new BDException("卡券创建失败");
			}
			//添加到表里面去
			StoreWxCard storeWxCard = new StoreWxCard();
			if(type == 1) { //创建门店会员卡
				storeWxCard.setCardId(cardId);
				storeWxCard.setMid(shopMemberId);
				storeWxCard.setType(1);
				storeWxCard.setTitle(shopMemeber.gettXiaoqu() + "会员卡");
			}else if(type == 2){ //创建商家全局优惠卡
				storeWxCard.setCardId(cardId);
				storeWxCard.setCentreId(shopMemeber.getCentreId());
				storeWxCard.setType(2);
				storeWxCard.setTitle(centre.getName() + "商户优惠卡");
			}
			storeWxCardMapper.insertSelective(storeWxCard);
		}
		resultMap.put("cardId", cardId);
		MemberWxcardExample cardExample = new MemberWxcardExample();
		cardExample.createCriteria().andCardIdEqualTo(cardId).andMidEqualTo(member.getId());
		List<MemberWxcard> memberWxcards = memberWxcardMapper.selectByExample(cardExample);
		if (ValidateUtil.isNotEmptyCollection(memberWxcards)) {
			resultMap.put("code", memberWxcards.get(0).getCode());
		}


		return resultMap;
	}



	@Override
	public Map<String, String> getAddCardExt(Long centerId, Long shopMemberId, int type) {
		StoreWxCardExample example = new StoreWxCardExample();
		if(type == 1){ //为1是领取会员卡
			example.createCriteria().andMidEqualTo(shopMemberId).andTypeEqualTo(1);
		}else if(type == 2){ //为2是领取商户卡
			example.createCriteria().andCentreIdEqualTo(centerId).andTypeEqualTo(2);
		}
		StoreWxCard storeWxCard = storeWxCardMapper.selectOneByExample(example);

		return wxService.getWxCardConfig(centerId, storeWxCard.getCardId());
	}

	@Override
	public BigDecimal getStoreProductPrice(Long shopMemberId) {
		return storeFreechargeMapper.getStoreProductPrice(shopMemberId);
	}
	public InputStream getImageStream(String url) {
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("GET");
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream inputStream = connection.getInputStream();
				return inputStream;
			}
		} catch (IOException e) {
			System.out.println("获取网络图片出现异常，图片路径为：" + url);
			e.printStackTrace();
		}
		return null;

	}
}
